
import axios from 'axios';
import md5 from 'md5';

import { createConnectionPool } from '../mysql/index.js'

const connection = await createConnectionPool()
// const axiosInstance = axios.create();
const baseURL = 'https://pay.147258.org'
const axiosInstance = axios.create({ baseURL });
axiosInstance.defaults.timeout = 5000;
axiosInstance.interceptors.request.use(async (config) => {
    config.headers['Content-Type'] = 'application/json';

    try {
        console.log('Getting token from Redis...');
        const [rows] = await connection.execute('SELECT * FROM token_store');
        const token_store = rows[0]
        console.log("查看:", rows);
        const token = token_store.token;
        const time = Date.now();

        if (token) {
            console.log('Token retrieved:', token);
            config.headers.Authorization = `${token}`;
            config.headers.Timestamp = time;
            config.headers.Sign = md5(time + `${token}naizi`);
        }

        return config;
    } catch (error) {
        console.error('Failed to get token:', error);
        return Promise.reject(error);
    }
}, error => {
    return Promise.reject(error);
});

export default axiosInstance;
